<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="68px">
      <el-form-item label="序列号" prop="serialNo">
        <el-input
          v-model="queryParams.serialNo"
          placeholder="请输入序列号"
          clearable
          size="small"
          style="width: 180px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button
                type="primary"
                icon="el-icon-plus"
                size="mini"
                @click="handleAdd"
            >新增</el-button>
            </el-col>
    </el-row>-->

    <!-- @selection-change="handleSelectionChange" -->
    <el-table v-loading="loading" :data="deviceList">
      <!-- <el-table-column type="selection" width="40" align="center" /> -->
      <el-table-column label="序号" align="center" prop="id" width="60" />
      <el-table-column label="序列号" align="center" prop="serialNo" :show-overflow-tooltip="true" />
      <el-table-column label="品牌" align="center" prop="brand" :show-overflow-tooltip="true" />
      <el-table-column label="设备ip" align="center" prop="deviceIp" :show-overflow-tooltip="true" />
      <el-table-column label="设备位置" align="center" prop="deviceAddr" :show-overflow-tooltip="true" />
      <el-table-column label="位置类型" align="center" prop="addrType" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <span v-if="scope.row.addrType == '1'">宿舍</span>
          <span v-else-if="scope.row.addrType == '2'">教学楼</span>
          <span v-else>其他</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <span v-if="scope.row.status == '2'">未绑定使用</span>
          <span v-else-if="scope.row.status == '1'">已绑定使用</span>
        </template>
      </el-table-column>
      <el-table-column
        label="已绑定的班级(宿舍)"
        align="center"
        prop="addrName"
        :show-overflow-tooltip="true"
      >
        <template slot-scope="scope">
          <span v-if="scope.row.addrName">{{ scope.row.addrName }}</span>
          <span v-else>---</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" width="180">
        <template slot-scope="scope">
          <!-- <el-tooltip content="修改" placement="top">
                    <el-button
                        size="mini"
                        circle type="success"
                        icon="el-icon-edit"
                        @click="handleUpdate(scope.row)"
                    />
          </el-tooltip>-->
          <el-tooltip content="绑定班级" placement="top">
            <el-button
              size="mini"
              circle
              type="info"
              icon="el-icon-connection"
              @click="handleBindCls(scope.row)"
              v-if="scope.row.status == '2' && scope.row.addrType == '2'"
            />
          </el-tooltip>
          <el-tooltip content="解绑班级" placement="top">
            <el-button
              size="mini"
              circle
              type="warning"
              icon="el-icon-link"
              @click="handleUnbindClass(scope.row)"
              v-if="scope.row.status == '1' && scope.row.addrType == '2'"
            />
          </el-tooltip>
          <el-tooltip content="绑定宿舍" placement="top">
            <el-button
              size="mini"
              circle
              type="info"
              icon="el-icon-connection"
              @click="handleBindDor(scope.row)"
              v-if="scope.row.status == '2' && scope.row.addrType == '1'"
            />
          </el-tooltip>
          <el-tooltip content="解绑宿舍" placement="top">
            <el-button
              size="mini"
              circle
              type="warning"
              icon="el-icon-link"
              @click="handleUnbindDor(scope.row)"
              v-if="scope.row.status == '1' && scope.row.addrType == '1'"
            />
          </el-tooltip>
          <el-tooltip content="删除" placement="top">
            <el-button
              size="mini"
              circle
              type="danger"
              icon="el-icon-delete"
              @click="deleteDevice(scope.row)"
            />
          </el-tooltip>
          <span v-if="scope.row.addrType == '3'">---</span>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- add -->
    <el-dialog :title="title" :visible.sync="open" width="35%">
      <el-form :model="form" ref="form" :rules="rules" label-width="90px">
        <el-form-item label="序列号" prop="serialNo">
          <el-input v-model="form.serialNo" />
        </el-form-item>
        <el-form-item label="品牌" prop="brand" label-width="90px">
          <el-input v-model="form.brand" />
        </el-form-item>
        <el-form-item label="设备ip" prop="deviceId" label-width="90px">
          <el-input v-model="form.deviceId" />
        </el-form-item>
        <el-form-item label="设备位置" prop="deviceAddr" label-width="90px">
          <el-input v-model="form.deviceAddr" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 绑定班级 -->
    <el-dialog :title="title" :visible.sync="clsOpen" width="30%">
      <el-form :model="bindForm" ref="bindForm" label-width="90px">
        <el-form-item label="设备ID" v-if="false">
          <el-input v-model="bindForm.deviceId" />
        </el-form-item>
        <el-form-item label="班级">
          <el-select v-model="bindForm.classId" placeholder="请选择班级" filterable>
            <el-option
              v-for="item in classOptions"
              :key="item.id"
              :label="item.className"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitBind">确 定</el-button>
        <el-button @click="close">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 绑定宿舍楼层 -->
    <el-dialog :title="title" :visible.sync="dorOpen" width="30%">
      <el-form :model="dorForm" ref="dorForm" label-width="90px">
        <el-form-item label="设备ID" v-if="false">
          <el-input v-model="dorForm.deviceId" />
        </el-form-item>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-form-item label="宿舍栋号" prop="buildingNo">
              <el-select v-model="dorForm.buildingNo" placeholder="宿舍栋号" clearable>
                <el-option
                  v-for="dict in buildingNoOptions"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-form-item label="楼层" prop="storey">
              <el-select v-model="dorForm.storey" placeholder="楼层">
                <el-option
                  v-for="dict in storeyOptions"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitBindDor">确 定</el-button>
        <el-button @click="closeDor">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  findPageList,
  addOrUpdate,
  findById,
  bindClass,
  unbindClass,
  bindDor,
  unbindDor,
  deleteDevice
} from "@/api/basedata/bdevice";
import { listAllBClass } from "@/api/basedata/bclass";
import { listAllBDormitory } from "@/api/basedata/bdormitory";

export default {
  name: "device",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      clsOpen: false,
      dorOpen: false,
      //table数据
      deviceList: [],
      //班级
      classOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        serialNo: undefined
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        serialNo: [{ required: true, message: "序列号必填", trigger: "blur" }]
      },
      //设备绑定班级表单
      bindForm: {
        deviceId: undefined,
        classId: undefined
      },

      dorForm: {
        deviceId: undefined,
        buildingNo: undefined,
        storey: undefined
      },
      // 宿舍栋号
      buildingNoOptions: [],
      // 楼层
      storeyOptions: []
    };
  },
  created() {
    this.getList();
    this.getAllClass();
    this.getDicts("sys_building").then(response => {
      this.buildingNoOptions = response.data;
    });
    this.getDicts("sys_storey").then(response => {
      this.storeyOptions = response.data;
    });
  },
  methods: {
    // deleteDevice({
    //     addrType: row.addrType,
    //     id: row.id
    //   }).then(res => {
    //     console.log(res);
    //     this.getList();
    //   });

    // 删除设备
    deleteDevice(row) {
      console.log(row);
      this.$confirm("是否确认删除该设备", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          deleteDevice({
            addrType: row.addrType,
            id: row.id
          }).then(res => {
            console.log(res);
            this.getList();
            if (res.code == 200) {
              this.$message({
                type: "success",
                message: "删除成功!"
              });
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    getList() {
      this.loading = true;
      findPageList(this.queryParams).then(resp => {
        this.deviceList = resp.data.list;
        this.total = resp.data.total;
        this.loading = false;
      });
    },

    getAllClass() {
      listAllBClass().then(resp => {
        this.classOptions = resp.data;
        // console.log(this.classOptions)
      });
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    // handleSelectionChange(selection) {
    //     this.studentOptions = selection
    //     this.ids = selection.map(item => item.id)
    //     this.single = selection.length!==1
    //     this.multiple = !selection.length
    // },

    handleAdd() {
      this.title = "新增";
      this.open = true;
      this.reset();
    },
    handleUpdate(row) {
      findById(row.id).then(resp => {
        this.form = resp.data;
        this.open = true;
        this.title = "修改";
      });
    },
    handleDelete(row) {},
    reset() {
      this.form = {
        id: undefined,
        serialNo: undefined,
        brand: undefined,
        deviceIp: undefined,
        deviceAddr: undefined
      };
      this.resetForm("form");
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          addOrUpdate(this.form).then(resp => {
            this.msgSuccess("提交成功");
            this.open = false;
            this.getList();
          });
        }
      });
    },
    //打开绑定页面
    handleBindCls(row) {
      this.title = "绑定班级";
      this.clsOpen = true;
      this.bindForm.deviceId = row.id;
      this.bindForm.classId = undefined;
    },
    //提交绑定
    submitBind: function() {
      bindClass(this.bindForm).then(resp => {
        if (resp.code === 200) {
          this.msgSuccess("绑定成功");
          this.clsOpen = false;
          this.getList();
        } else {
          this.msgError(response.message);
        }
      });
    },
    //关闭绑定页面
    close() {
      this.clsOpen = false;
      this.bindForm = {
        deviceId: undefined,
        classId: undefined
      };
    },
    //解绑班级
    handleUnbindClass(row) {
      this.$confirm("此操作将解除设备与班级的绑定关系, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          unbindClass(row.id).then(resp => {
            if (resp.code === 200) {
              this.getList();
            } else {
              this.msgError(response.message);
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消"
          });
        });
    },
    handleBindDor(row) {
      this.title = "绑定宿舍楼层";
      this.dorOpen = true;
      this.dorForm.deviceId = row.id;
      //   this.bindForm.classId = undefined;
    },
    closeDor() {
      this.dorOpen = false;
      this.bindForm = {
        deviceId: undefined,
        buildingNo: undefined,
        storey: undefined
      };
    },
    submitBindDor: function() {
      console.log(this.dorForm);
      bindDor(this.dorForm).then(resp => {
        if (resp.code === 200) {
          this.msgSuccess("绑定成功");
          this.dorOpen = false;
          this.getList();
        } else {
          this.msgError(response.message);
        }
      });
    },

    handleUnbindDor(row) {
      this.$confirm("此操作将解除设备与宿舍楼层的绑定关系, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          unbindDor(row.id).then(resp => {
            if (resp.code === 200) {
              this.getList();
            } else {
              this.msgError(response.message);
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消"
          });
        });
    }
  }
};
</script>

<style>
</style>